package OrderService

import (
	"context"
	"errors"
	"fmt"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/service-other/GoodsActivityService"
	"github.com/gogf/gf/util/gconv"
	"math"
	"strconv"
)

// 根据活动ID，计算优惠
func goodsActivityModelById(ctx context.Context, createModel *OrderResp.OrderItem, activityId int) error {
	activityNow, err := GoodsActivityService.GetGoodsActivityById(ctx, activityId)
	if err != nil {
		return err
	}
	if activityNow == nil {
		return errors.New("找不到活动")
	}
	var totalPrice int64 = 0
	// 先计算 当前分组全部总价
	for _, item := range createModel.Goodss {
		totalPrice += item.Paid
	}

	fmt.Println("总价 ", totalPrice)
	// 计算出总的优惠价
	_, discountMoney, err := GoodsActivityService.GetMaxDiscountActivity([]*entity.GoodsActivity{
		activityNow,
	}, totalPrice)
	if err != nil {
		return err
	}

	fmt.Println("总的优惠价 ", discountMoney)

	// 保持一致性优惠
	var discountMoney2 int64 = 0
	// 分摊到商品上面
	for _, item := range createModel.Goodss {
		// 向上取整的方式
		tmpMoney := math.Ceil(float64(item.Paid) / float64(totalPrice) * float64(discountMoney))
		item.ActivityDiscountMoney = gconv.Int64(strconv.FormatFloat(tmpMoney, 'f', 0, 64))
		discountMoney2 += item.ActivityDiscountMoney
		item.Paid = item.Paid - item.ActivityDiscountMoney
		// 不能小于1分钱
		if item.Paid < 1 {
			// 重算，设置最少 1 分钱
			item.ActivityDiscountMoney -= 1
			item.Paid = 1
			discountMoney2 -= 1
		}
	}

	// 矫正优惠
	if discountMoney2 > discountMoney {
		tmpGoods := createModel.Goodss[0]
		tmpGoods.ActivityDiscountMoney += discountMoney - discountMoney2
		tmpGoods.Paid = tmpGoods.Options[0].SellPrice*int64(tmpGoods.BuyNum) - tmpGoods.ActivityDiscountMoney
	}
	// 少了
	if discountMoney > discountMoney2 {
		tmpGoods := createModel.Goodss[0]
		tmpGoods.ActivityDiscountMoney += discountMoney - discountMoney2
		tmpGoods.Paid = tmpGoods.Options[0].SellPrice*int64(tmpGoods.BuyNum) - tmpGoods.ActivityDiscountMoney
	}
	createModel.ActivityDiscountMoney = discountMoney
	createModel.GroupId = activityNow.Id

	for _, item := range createModel.Goodss {
		// 实付 金额 不能为负数
		if item.Paid < 1 {
			return errors.New(item.GoodsName + " 实付金额为负数")
		}
		item.ActivityPaid = item.Paid
		item.ActivityId = activityNow.Id
	}

	return nil
}
